<template>
  <el-checkbox-group v-model="localValues" class="checkbox-with-sub">
    <div v-for="opt in options" :key="opt.value" class="option-row">
      <el-checkbox :value="opt.value">
        <div class="option-content">
          <span>{{ opt.label }}</span>
          <span v-if="opt.otherLabel && localValues.includes(opt.value)" class="other-label">{{ opt.otherLabel }}</span>
          <template v-if="opt.izSub && localValues.includes(opt.value)">
            <span v-if="opt.subTitle" class="sub-title">{{ opt.subTitle }}</span>
            <el-input v-model="subInputs[opt.value]" size="small" class="sub-input" style="width: 120px; margin-left: 8px" />
          </template>
        </div>
      </el-checkbox>
    </div>
  </el-checkbox-group>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from "vue"

const props = defineProps<{
  modelValue: string[]
  options: Array<{
    value: string
    label: string
    izSub?: boolean
    subTitle?: string
  }>
}>()

const emit = defineEmits(["update:modelValue", "change"])

const localValues = ref<string[]>([])
const subInputs = ref<Record<string, string>>({})

function parseModelValue(val: string[]): { values: string[]; subMap: Record<string, string> } {
  const values: string[] = []
  const subMap: Record<string, string> = {}

  ;(val || []).forEach((item) => {
    if (item.includes(":")) {
      const [v, sub = ""] = item.split(":")
      values.push(v)
      subMap[v] = sub
    } else {
      values.push(item)
    }
  })

  // 补充缺失的 izSub 字段，防止 undefined
  props.options.forEach((opt) => {
    if (opt.izSub && !(opt.value in subMap)) {
      subMap[opt.value] = ""
    }
  })

  return { values, subMap }
}

// 初始化
onMounted(() => {
  const { values, subMap } = parseModelValue(props.modelValue)
  localValues.value = values
  subInputs.value = subMap
})

// modelValue 外部变更（防止死循环）
watch(
  () => props.modelValue,
  (newVal) => {
    const { values, subMap } = parseModelValue(newVal)
    const newStr = JSON.stringify(values) + JSON.stringify(subMap)
    const oldStr = JSON.stringify(localValues.value) + JSON.stringify(subInputs.value)

    if (newStr !== oldStr) {
      localValues.value = values
      subInputs.value = subMap
    }
  },
  { immediate: true }
)

// localValues 改变
watch(localValues, (vals) => {
  emitModelValue()
})

// subInputs 改变
watch(
  () => subInputs.value,
  () => {
    emitModelValue()
  },
  { deep: true }
)

// 拼接结果
function emitModelValue() {
  try {
    const result = localValues.value.map((val) => {
      const opt = props.options.find((o) => o.value === val)
      if (opt?.izSub) {
        return `${val}:${subInputs.value[val] ?? ""}`
      }
      return val
    })

    nextTick(() => {
      emit("update:modelValue", result)
      emit("change", result)
    })
  } catch (e) {
    console.error("CheckboxWithSubInput emit error:", e)
  }
}
</script>

<style scoped>
.checkbox-with-sub {
  display: flex;
  flex-direction: column;
}
.option-row {
  /* margin-bottom: 8px; */
}
.option-content {
  display: inline-block;
  align-items: center;
  flex-wrap: wrap;
  margin-right: 0;
}
.sub-title {
  margin-left: 8px;
  color: #666;
  font-size: 14px;
}
.other-label {
  margin-left: 10px;
  font-weight: 600;
  color: red !important; /* 强制覆盖 Element Plus 默认颜色 */
}
/* 强制 label 自动换行 */
:deep(.el-checkbox) {
  align-items: center;
}
:deep(.el-checkbox__label) {
  white-space: normal !important;
  word-break: break-word;
  line-height: 1.1 !important;
}
</style>
